#include "../include/fast.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <signal.h>
#include <netinet/ip.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include "net.h"
#define ctoe_port 5555//防御控制器和防御执行器之间通信端口号
int sock;
//ctrl+C停止操作前需要关闭socket，以及清零寄存器
void stop(int signo) {
  close(sock);
  if(fast_reg_rd(0x25800)!=0x0){
    fast_reg_wr(0x25800,0x0);
  }
  printf("已经关闭socket,寄存器已清零\n");
  exit(0);
}
int main(int argc,char* argv[]){

  int val;
//  unsigned int ip;
  sock=get_server_socket(ctoe_port);
  if(sock < 0) {
  printf("can't get right socket\n");
    return -1;
  }
  printf("connect to server successfully!\n");

  /*初始化平台硬件*/
	fast_init_hw(0,0);
  //初始化寄存器，并打印寄存器值
  int flag=fast_reg_rd(0x25800);
  printf("初始寄存器值为：%x\n",flag);
  if(flag!=0x0){
    fast_reg_wr(0x25800,0x0);
  }
  //注册ctrl+C停止信号
  signal(SIGINT,stop);
  while(1){
    char atack_type;
    printf("wating for massages...\n");
    //接收防御控制器消息
		val = recv_msg(sock,&atack_type,1);
		if(val<=0){
			printf("recv_msg error\n");
			continue;
		}
		if(atack_type==0){//atack_type==0表示停止防御
      printf("get alert cancel\n");
      if(fast_reg_rd(0x25800)!=0x0){//避免重复写入
        //写寄存器  TCP防御开关地址：0x25800  0x0为关闭
        fast_reg_wr(0x25800,0x0);
        printf("寄存器值：%x\n",fast_reg_rd(0x25800));
      }
		}else{//atack_type不为0 表示有攻击
      printf("get atack_type!!\n");
      if(fast_reg_rd(0x25800)!=0x1){//避免重复写入
        //写寄存器  TCP防御开关地址：0x25800   0x1为开启
        sleep(5);
        fast_reg_wr(0x25800,0x1);
        printf("寄存器值：%x\n",fast_reg_rd(0x25800));
      }
		}
  }
  close(sock);
  return 0;
}
